#include <stdio.h>
#include <windows.h>

#include "config.h"
#include "event.h"
#include "util.h"

void update_crc(struct config *conf);

int
main(int argc, char **argv)
{
	FILE *fp;
	char *out_file;
	int r;
	int i;
	struct config config;

	if (argc < 5 || (argc - 2) % 3) {
		fprintf(stderr, "usage: %s out_file interval mode pid "
		    "[interval mode pid] [...]\n", argv[0]);
		exit(1);
	}

	out_file = argv[1];

	argc -= 2;
	argv += 2;
	
	memset(&config, 0, sizeof(config));

	for (i = 0; i < NUM_LOG_SLOTS; ++i) {
		if (argc < 3)
			break;
		config.event[i].interval = atoi(argv[0]);
		config.event[i].mode = atoi(argv[1]);
		config.event[i].pid = atoi(argv[2]);
		argc -= 3;
		argv += 3;
#if 0
		printf("int: %d, mode: %d, pid: %d\n",
		    config.event[i].interval, config.event[i].mode,
		    config.event[i].pid);
#endif
	}

	update_crc(&config);
	if (!valid_config(&config)) {
		fprintf(stderr, "error: error creating config.\n");
		exit(1);
	}

	dump_config(&config);

	fp = fopen(out_file, "w+b");
	if (fp == NULL) {
		fprintf(stderr, "error: could not open %s\n", out_file);
		exit(1);
	}

	r = fwrite(&config, 1, sizeof(config), fp);
	if (r != sizeof(config)) {
		fprintf(stderr, "error: could not write config\n");
		exit(1);
	}

	fclose(fp);

	return 0;
}

void
update_crc(struct config *conf)
{
	uint8_t *p;
	uint16_t crc;
	int i;

	p = (uint8_t *) conf;

	conf->crc = 0;
	crc = 0xffff;
	for (i = 0; i < sizeof(*conf); ++i) {
		crc = crc16_update(crc, *p);
		++p;
	}

	conf->crc = crc;
}
